package com.smm.web.vmc.handler;

import com.smm.web.vmc.domain.Alam;
import com.smm.web.vmc.domain.Camera;
import com.smm.web.vmc.domain.Tag;
import com.smm.web.vmc.domain.User;
import com.smm.web.vmc.service.AlamService;
import com.smm.web.vmc.service.CameraService;
import com.smm.web.vmc.service.TagService;
import com.smm.web.vmc.service.UserReceiptRelationService;
import com.smm.web.vmc.util.PushUtilImpl;
import com.smm.web.vmc.util.SMSUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhenghao on 2016/8/26.
 *
 */
@Slf4j
public class RfidHandler extends IoHandlerAdapter {


    private static Map<String , Date> map=new HashMap<>();

    @Resource
    private TagService tagService;

    @Resource
    private CameraService cameraService;

    @Resource
    private AlamService alamService;

    @Resource
    private UserReceiptRelationService userReceiptRelationService;

    @Resource(name = "gePushUtil")
    private PushUtilImpl pushUtil;

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {

        //获取标签信息
        TagInfo tagInfo = TagInfo.decodeMessage((String) message);

        //如果数据不正确，或者不是震动事件，不做任何处理
        if(tagInfo==null || !tagInfo.isShock() ) return;

        log.info("编号为："+tagInfo.getTagNo()+" 的标签发生震动，开始处理报警");

        //处理震动事件
        disposeAlam(tagInfo);

    }


    //处理报警信息
    private void disposeAlam(TagInfo tagInfo){

        try{

            //检查是否重复报警，如果是，不做任何处理
            if(checkRepalyAlam(tagInfo)) return;

            //查询标签对应的摄像头
            Tag tag = tagService.getOneById(tagInfo.getTagNo());

            if(tag==null) {

                log.info("编号为："+tagInfo.getTagNo()+" 的标签记录在数据库中不存在。报警处理结束");

                return ;
            }

            log.info(tag.getCamera().getIp());
            log.info(tag.getReceipt().getNo());

            String captureImageUrl = "";    //抓拍图片访问地址

            Camera camera = tag.getCamera();

            //检查标签是否有关联摄像头
            if(camera==null){

                log.info("编号为："+tag.getNo()+" 的标签未绑定摄像头");

            }else{
                //执行抓拍
//                captureImageUrl = cameraService.capture(camera);
                captureImageUrl = this.cameraService.captureByAPI(camera);
            }

            //保存报警信息
            Alam alam = new Alam();
            alam.setTag(tag);
            alam.setAlamTime(new Date());
            alam.setCaptureImageUrl(captureImageUrl);
            alam.setReceipt(tag.getReceipt());

            alamService.add(alam);

            //推送报警信息到仓单关联用户
            List<User> userList = this.userReceiptRelationService.getUserByReceipt(tag.getReceipt().getNo());

            pushUtil.sendByUserList("仓单报警通知","仓单："+tag.getReceipt().getNo()+" 发生震动报警",userList);


            log.info("app推送通知发送完成. 仓单编号："+tag.getReceipt().getNo());

            //发送短信通知

            log.info("发送短信通知. 仓单编号："+tag.getReceipt().getNo());

            SMSUtil.send(userList,tag.getReceipt().getNo(),new Date());

            log.info("短信发送完成");


        }catch (Exception e){

            log.info("报警信息处理异常");

            e.printStackTrace();

            log.error(String.valueOf(e));
        }

    }

    private boolean checkRepalyAlam(TagInfo info) {

        Date date = new Date();

        //检查是否存在，不存在，直接返回 false
        if(!map.containsKey(info.getTagNo())){
            map.put(info.getTagNo(), date);
            return false;
        }


        //检查是否1分钟内重复报警
        long times=date.getTime()-map.get(info.getTagNo()).getTime();

        //如果超过1分钟
        if(times>60*1000){

            map.remove(info.getTagNo());     //删除原记录

            map.put(info.getTagNo(), date);  //重新保存报警时间

            return false;
        }else{

            log.info("标签："+info.getTagNo()+" 1分钟内重复报警");
        }

        return true;

    }


}
